﻿<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
include __ROOT__ . "../Ry/rongcloud.php";

/*
	用户
 */
class Users extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('M_user');
		$this->load->model('M_quantification_user');
		$this->load->model('M_quantification_user_map');
		$this->load->model('M_sendmess');
        		$this->load->model('M_emergency_mouldaccept');
        		$this->load->model('M_emergency');
        		$this->load->model('M_emergency_task_sub');


	}

	/**获取token
	 *@param $PID
	*/
	public function token($userid,$username,$uri){
		$appKey = '8luwapkubqwsl';
		$appSecret = 'NIwaigSmzy5';
		$RongCloud = new RongCloud($appKey,$appSecret);
		if(empty($userid)){
		       exit(json_encode(array('code'=>1,'info'=>'用户pid不能为空')));
		}
		if(empty($username)){
		       exit(json_encode(array('code'=>1,'info'=>'用户名称不能为空')));
		}
		if(empty($uri)){
		       exit(json_encode(array('code'=>1,'info'=>'头像地址不能为空')));
		}
		// 获取 Token 方法
		$result = $RongCloud->user()->getToken($userid, $username, $uri);
	             $result = json_decode($result,1);
	             $save_data['token'] = $result['token'];
	             $res = $this->M_user->updateData($save_data,array('user_id'=>$userid));
	             // $this->printJson_data($result['token']);
	             return $result['token'];
	}
	  //推送
    //$fromUserId 发送人id
    //$toUserId 接收人id
    //$title 标题
    //$con 内容
    //$taskid 任务id
    //$type 类型
    public function push($fromUserId,$toUserId,$title,$con,$taskid,$type){
        $appKey = '8luwapkubqwsl';
        $appSecret = 'NIwaigSmzy5';
        $RongCloud = new RongCloud($appKey,$appSecret);
            $content = '{"content":"'.$title.'","extra":"'.$con.'"}';
            $result = $RongCloud->message()->PublishSystem($fromUserId, ["$toUserId"], 'RC:TxtMsg',"$content", 'thisisapush', '{\"pushData\":\"hello\"}', '0', '0');
            $data1 = array(
                'taskid'=>$taskid,
                'type'=>$type,
                'sendid'=>$fromUserId,
                'pubid'=>$toUserId,
                'title'=>$title,
                'content'=>$con,
                'time'=>time(),
            );
            $insert_id1 = $this->M_sendmess->saveData($data1);
            return $result;
    }

	/*public function push(){
		$appKey = '8luwapkubqwsl';
		$appSecret = 'NIwaigSmzy5';
		$jsonPath = "../Ry/jsonsource/";
		$RongCloud = new RongCloud($appKey,$appSecret);
		// 广播消息方法（fromuserid 和 message为null即为不落地的push）
		$result = $RongCloud->push()->broadcastPush('{"platform":["ios","android"],"audience":{"userid":["1","2"]},"notification":{"alert":"this is a push"}}');
		print_r($result);
	}*/

	/*
		登录
	 */
	public function login()
	{

		$user_account = $this->input->post('user_account');		//账号
		$user_pwd = $this->input->post('user_pwd');			//密码
		// $user_account = 1002;
		// $user_pwd = 666666;
		$data['is_online'] = 1;
		if(empty($user_account))
		{
			$res['code'] = 2;
			$res['info'] = "用户名不能为空";
		}else if(empty($user_pwd)){
			$res['code'] = 3;
			$res['info'] = "密码不能为空";
		}else{
			$user_pwd = md5($user_pwd);
			$user = $this->db->select('user_id')
					   ->from('t_user')
					   ->where(['user_account' => $user_account,'is_del' => 1])
					   ->get()
					   ->row_array();
			if(empty($user))
			{
				$res['code'] = 4;
				$res['info'] = "账号不存在";
			}else{
				$result = $this->db->select('user_id,user_name,user_img,t_user.post_id,post_name,user_level,token,is_closure')
						     ->from('t_user')
						     ->join('t_post','t_post.post_id = t_user.post_id','left')
						     ->where(['user_account'=>$user_account,'user_pwd'=>$user_pwd])
						     ->get()
						     ->row_array();
				if(!empty($result['user_id']))
				{
					if($result['is_closure'] == 1)
					{
						//token验证登录
						if($result['token'] == '')
						{
							$data['token'] = $this->token($result['user_id'],$result['user_name'],$result['user_img']);
							$result2 = $this->db->where('user_id',$result['user_id'])
									->update('t_user',$data);
							$result['token'] = $data['token'];
						}else{
							$result2 = $this->db->where('user_id',$result['user_id'])
									->update('t_user',$data);
						}
						$res['code'] = 0;
						$res['info'] = "成功";
						$res['data'] = $result;
					}else{
						$res['code'] = 2;
						$res['info'] = "该用户已被封禁，登录失败";
					}
				}else{
					$res['code'] = 1;
					$res['info'] = "密码错误";
				}
			}
		}

		echo json_encode($res);
		
	}

	/*
		个人资料
	 */
	public function user_list()
	{

		$user_id = $this->input->post('user_id');
		// $user_id = 3;
		$list = $this->db->select('user_name,user_account,user_img,department_name,user_sex,user_phone,user_tel')
				->from('t_user')
				->join('t_department','t_department.department_id = t_user.department_id','left')
				->where('user_id',$user_id)
				->get()
				->row_array();
		if($list)
		{
			$list['user_img'] = base_url().$list['user_img'];
			$res['code'] = 0;
			$res['info'] = "成功";
			$res['data'] = $list;
		}else{
			$res['code'] = 1;
			$res['info'] = "暂无数据";
			$res['data'] = array();
		}
		
		echo json_encode($res);

	}

	/*
		修改密码
	 */
	public function up_pwd()
	{

		$data['user_id'] = $this->input->post('user_id');			//用户id
		$data['old_pwd'] = $this->input->post('old_pwd');			//旧密码
		$data['new_pwd'] = $this->input->post('new_pwd');		//新密码
		$data['user_pwd'] = $this->input->post('user_pwd');		//确认新密码
		// $data['user_id'] = 1;
		// $data['old_pwd'] = 666666;
		// $data['new_pwd'] = 111111;
		// $data['user_pwd'] = 111111;
		$data['old_pwd'] = md5($data['old_pwd']);
		$data['new_pwd'] = md5($data['new_pwd']);
		$data['user_pwd'] = md5($data['user_pwd']);
		// print_r($data);die;
		if($data['new_pwd'] == $data['user_pwd'])
		{
			$list = $this->db->select('user_pwd')
					->from('t_user')
					->where('user_id',$data['user_id'])
					->get()
					->row_array();
			if($data['old_pwd'] == $list['user_pwd'])
			{
				if($data['old_pwd'] == $data['new_pwd'])
				{
					$res['code'] = 2;
					$res['info'] = "新旧密码相同，请重新输入";
				}else{
					unset($data['old_pwd']);
					unset($data['new_pwd']);
					$results = $this->db->where('user_id',$data['user_id'])
							->update('t_user',$data);
					if($results)
					{
						$res['code'] = 0;
						$res['info'] = "密码修改成功";
					}else{
						$res['code'] = 1;
						$res['info'] = "密码修改失败";
					}
				}
			}else{
				$res['code'] = 3;
				$res['info'] = "旧密码错误，请重新输入";
			}
		}else{
			$res['code'] = 4;
			$res['info'] = "两次输入的新密码不同，请重新输入";
		}
		

		echo json_encode($res);

	}

	/*
		组织架构列表
	 */
	public function organize_list()
	{

		$list = $this->db->select('department_id,department_name,p_id')
				->from('t_department')
				->get()
				->result_array();
		foreach($list as $k => $v)
		{
			$user_list = $this->db->select('user_id,user_name,user_job')
					->from('t_user')
					->where('department_id',$v['department_id'])
					->get()
					->result_array();
			if(!empty($user_list))
			{
				$list[$k]['user'] = $user_list;
			}
		}
		$arr = $this->get_attr($list,0,'child');
		if($arr)
		{
			$res['code'] = 0;
			$res['info'] = "获取组织架构列表成功";
			$res['data'] = $arr;
		}else{
			$res['code'] = 1;
			$res['info'] = "暂无数据";
			$res['data'] = array();
		}
		// print_r($arr);die;
		echo json_encode($res);

	}

	/*
		无限极分类方法
	 */
	public function get_attr($a,$pid,$children){  
		$tree = array();                                //每次都声明一个新数组用来放子元素  
		foreach($a as $v){  
			if($v['p_id'] == $pid){                      //匹配子记录  
				$v[$children] = $this->get_attr($a,$v['department_id'],$children.'s'); //递归获取子记录  
				if($v[$children] == null){  
					unset($v[$children]);             //如果子元素为空则unset()进行删除，说明已经到该分支的最后一个元素了（可选）  
				}  
				$tree[] = $v;                           //将记录存入新数组  
			}  
		}  
		return $tree;                                  //返回新数组  
	}  

	/*
		无限极分类方法
	 */
	// public function make_tree($list,$pk='department_id',$pid='p_id',$child='child',$root=0)
	// {
	// 	$tree=array();
	// 	$packData=array();
	// 	foreach ($list as $data) 
	// 	{
	// 		$packData[$data[$pk]] = $data;
	// 	}
	// 	foreach ($packData as $key =>$val)
	// 	{
	// 		if($val[$pid]==$root)//代表跟节点
	// 		{
	// 			$tree[]=& $packData[$key];
	// 		}else{
	// 		//找到其父类
	// 		$packData[$val[$pid]][$child][]=& $packData[$key];
	// 		}
	// 	}
	// 	return $tree;
	// }
	
	/*
		修改个人资料
	 */
	public function edit_user()
	{

		$data = $this->input->post();
		$result = $this->db->where('user_id',$data['user_id'])
				->update('t_user',$data);
		if($result)
		{
			$res['code'] = 0;
			$res['info'] = "修改个人资料成功";
		}else{
			$res['code'] = 1;
			$res['info'] = "修改个人资料失败";
		}

		echo json_encode($res);

	}

	/*
		登岗
	 */
	public function login_post()
	{

		/*
			接值
		 */
		$user_id = $data['user_id'] = $this->input->post('user_id');
		$post_id = $arr['post_id'] = $data['post_id'] = $this->input->post('post_id');
		$post_name = $data['post_name'] = $this->input->post('post_name');
		// $user_id = 2;
		// $post_id = 4;
		// $post_name = '火车';
		$data['up_time'] = time();
		/*
			登岗记录表插入数据
		 */
		$result1 = $this->db->insert('t_post_record',$data);
		$arr['post_record_id'] = $this->db->insert_id();
		/*
			用户表插入岗位id和登岗记录id
		 */
		$result2 = $this->db->where('user_id',$user_id)
				->update('t_user',$arr);
		if($result1 && $result2)
		{
			$this->create_post_task($user_id,$post_id);
			$this->create_em_task($user_id,$post_id);
			$this->task_start_day($user_id,$post_id);
			$res['code'] = 0;
			$res['info'] = "登岗成功";
		}else{
			$res['code'] = 1;
			$res['info'] = "登岗失败";
		}

		echo json_encode($res);
		/*$data['user_id'] = $this->input->post('user_id');
		$data['post_id'] = $this->input->post('post_id');
		$data['post_name'] = $this->input->post('post_name');
		$data['up_time'] = time();
		$aa['post_id'] = $data['post_id'];
		$result = $this->db->insert('t_post_record',$data);
		$aa['post_record_id'] = $this->db->insert_id();
		$result2 = $this->db->where('user_id',$data['user_id'])
				->update('t_user',$aa);
		if($result && $result2)
		{
			$this->create_post_task($data['user_id'],$data['post_id']);
			$this->task_start_day($data['user_id'],$data['post_id']);
			$res['code'] = 0;
			$res['info'] = "登岗成功";
		}else{
			$res['code'] = 1;
			$res['info'] = "登岗失败";
		}

		echo json_encode($res);*/

	}

	/*
		切岗
	 */
	public function check_post()
	{

		/*
			接值
		 */
		$user_id = $brr['user_id'] = $this->input->post('user_id');
		$post_id = $crr['post_id'] = $brr['post_id'] = $this->input->post('post_id');
		$post_name = $brr['post_name'] = $this->input->post('post_name');
		// $user_id = $brr['user_id'] = 55;
		// $post_id = $crr['post_id'] = $brr['post_id'] = 126;
		// $post_name = $brr['post_name'] = 'aa';
		$arr['down_time'] = time();
		/*
			通过用户id获取登岗记录id
		 */
		$result1 = $this->db->select('post_record_id,post_type_id')
				->from('t_user')
				->join('t_post','t_post.post_id = t_user.post_id')
				->where('user_id',$user_id)
				->get()
				->row_array();
		if($result1['post_type_id'] == 2)
		{
			/*
				原登岗记录插入下岗时间
			 */
			$result2 = $this->db->where('post_record_id',$result1['post_record_id'])
					->update('t_post_record',$arr);
			/*
				登岗记录表插入新的登岗数据
			 */
			$brr['down_time'] = time();
			$result3 = $this->db->insert('t_post_record',$brr);
			$crr['post_record_id'] = $this->db->insert_id();
			/*
				更新用户表岗位id和登岗记录id
			 */
			$result4 = $this->db->where('user_id',$user_id)
					->update('t_user',$crr);
			if($result4)
			{
				$this->create_post_task($user_id,$post_id);
				$this->create_em_task($user_id,$post_id);
				$this->task_start_day($user_id,$post_id);
				$res['code'] = 0;
				$res['info'] = "切岗成功";
			}else{
				$res['code'] = 1;
				$res['info'] = "切岗失败";
			}
		}else{
			if($result1['post_type_id'] == 1)
			{
				$res['code'] = 2;
				$res['info'] = "作业人员不能切岗";
			}else{
				$res['code'] = 3;
				$res['info'] = "您暂未登岗,请登岗后进行切岗操作";
			}
		}

		echo json_encode($res);
		/*$aa['user_id'] = $this->input->post('user_id');
		$bb['post_id'] = $aa['post_id'] = $this->input->post('post_id');
		$aa['post_name'] = $this->input->post('post_name');
		$aa['up_time'] = time();
		$data['down_time'] = time();
		$list = $this->db->select('post_record_id')
				->from('t_user')
				->where('user_id',$aa['user_id'])
				->get()
				->row_array();
		if($list['post_record_id'])
		{
			$result = $this->db->where('post_record_id',$list['post_record_id'])
					->update('t_post_record',$data);
			$result2 = $this->db->insert('t_post_record',$aa);
			$bb['post_record_id'] = $this->db->insert_id();
			$result3 = $this->db->where('user_id',$aa['user_id'])
					->update('t_user',$bb);
			if($result && $result2 && $result3)
			{
				$this->create_post_task($aa['user_id'],$aa['post_id']);
				$this->task_start_day($aa['user_id'],$aa['post_id']);
				$res['code'] = 0;
				$res['info'] = "切岗成功";
			}else{
				$res['code'] = 1;
				$res['info'] = "切岗失败";
			}
		}else{
			$res['code'] = 2;
			$res['info'] = "您还未登岗";
		}

		echo json_encode($res);*/

	}

	/*
		退岗
	 */
	public function quit_post()
	{

		$user_id = $this->input->post('user_id');
		$post_id = $this->input->post('post_id');
		// $user_id = 2;
		// $post_id = 4;
		$arr['down_time'] = time();
		$brr['post_id'] = Null;
		$brr['post_record_id'] = Null;
		$brr['is_online'] = 0;
		$crr['is_online'] = 0;
		if(isset($post_id)){
			$result1 = $this->db->select('post_type_id')
					->from('t_post')
					->where('post_id',$post_id)
					->get()
					->row_array();
			if($result1['post_type_id'] == 2)
			{
				$result2 = $this->db->select('post_record_id')
						->from('t_user')
						->where('user_id',$user_id)
						->get()
						->row_array();
				$result3 = $this->db->where('post_record_id',$result2['post_record_id'])
						->update('t_post_record',$arr);
				if($result3)
				{
					$result4 = $this->db->where('user_id',$user_id)
							->update('t_user',$brr);
					if($result4)
					{
						$res['code'] = 0;
						$res['info'] = "作业岗位退岗并退出成功";
					}else{
						$res['code'] = 1;
						$res['info'] = "作业岗位退岗失败";
					}
				}else{
					$res['code'] = 1;
					$res['info'] = "作业岗位退岗失败";
				}
				
			}else{
				$result5 = $this->db->where('user_id',$user_id)
						->update('t_user',$crr);
				$res['code'] = 2;
				$res['info'] = "作业人员退出成功";
			}
		}else{
			$result5 = $this->db->where('user_id',$user_id)
					->update('t_user',$crr);
			if($result5)
			{
				$res['code'] = 3;
				$res['info'] = "作业岗位未登岗人员退出成功";
			}
		}

		echo json_encode($res);
		/*$user_id = $this->input->post('user_id');
		$post_id = $this->input->post('post_id');
		if(!empty($post_id))
		{
			$list2 = $this->db->select('post_type_id')
					->from('t_post')
					->where('post_id',$post_id)
					->get()
					->row_array();
			if($list2['post_type_id'] == 2)
			{
				$list = $this->db->select('post_record_id')
						->from('t_user')
						->where('user_id',$user_id)
						->get()
						->row_array();
				$data['down_time'] = time();
				$aa['post_id'] = Null;
				$aa['post_record_id'] = Null;
				if(!empty($list['post_record_id']))
				{
					$result = $this->db->where('post_record_id',$list['post_record_id'])
							->update('t_post_record',$data);
					$result2 = $this->db->where('user_id',$user_id)
							->update('t_user',$aa);
				}
				if($result && $result2)
				{
					$res['code'] = 0;
					$res['info'] = "退岗成功";
				}else{
					$res['code'] = 1;
					$res['info'] = "退岗失败";
				}
			}else{
				$res['code'] = 0;
				$res['info'] = "退出成功";
			}
		}else{
			$res['code'] = 0;
			$res['info'] = "退出成功";
		}

		echo json_encode($res);*/

	}

	/*
		岗位列表
	 */
	public function post_list()
	{

		$user_id = $this->input->post('user_id');
		// $user_id =8;
		$list1 = $this->db->select('t_user.department_id,t_user.post_id,t_post.post_type_id')
				->from('t_user')
				->join('t_post','t_post.post_id = t_user.post_id','left')
				->where('user_id',$user_id)
				->get()
				->row_array();
		if($list1['post_type_id'] == 1)
		{
			$list = array();
		}else{
			$id = $list1['department_id'];
			$department_id = $this->get_top_parentid($id);
			// print_r($department_id);die;
			$list = $this->db->select('post_id,post_name')
					->from('t_post')
					->where(['department_id' => $department_id,'post_type_id' => 2])
					->get()
					->result_array();
		}
		if(!empty($list))
		{
			$res['code'] = 0;
			$res['info'] = "获取岗位列表成功";
			$res['data'] = $list;
		}else{
			$res['code'] = 1;
			$res['info'] = "暂无数据";
			$res['data'] = array();
		}

		// print_r($list);die;
		echo json_encode($res);

	}

	/*
		通过子级id获取顶级id
	 */
	public function get_top_parentid($id){  

		$result = $this->db->select('department_id,p_id')
				->from('t_department')
				->where('department_id',$id)
				->get()
				->row_array();
		if($result['p_id'] != 0)
		{
			return $this->get_top_parentid($result['p_id']);
		}
		return $result['department_id'];
		
	}  

	//每天单点生成线上量化任务（针对岗位）未完成
    public function task_start_day($pid,$workid)
    {
//        $pid = getParam($this->input->get_post("userid", true), 'int',0);//用户id
//    $pid=67;
//        $workid = getParam($this->input->get_post("workid", true), 'int',0);//岗位id
//    $workid=2;
    $time = time();
        if(empty($pid) || empty($workid))
        {
            // $dd['code'] = 1;
            // $dd['info'] ='失败';
            // exit(json_encode(array('code'=>1,'info'=>'失败！')));
            return false;
        }
        $sql = "select q.* from t_quantification q  where q.quantification_post_type=3 and q.is_del=1 and q.quantification_start_time<=$time and q.quantification_user=$workid";
        $quanti = $this->M_quantification_user_map->querylist($sql);
        if(count($quanti)==0)
        {
            // exit(json_encode(array('code'=>1,'info'=>'当前岗位无任务！')));
            return false;
        }
        $dd['info'] = "成功";
        $time = time();
        $n=date("H");
        $n = intval($n);
        //获取当天的年份
        $y = date("Y");
        //获取当天的月份
        $m = date("m");
        //获取当天的号数
        $d = date("d");
        //上线的任务   每天单点 判断是否生成任务
        $tables = array('t_quantification'=>'q','t_quantification_user'=>'u');
        $join = array('q.quantification_id=u.quantification_id');
        $sql1 = "SELECT `q`.*, `u`.`quantification_user_id` as `userid` FROM `t_quantification` As `q` LEFT JOIN `t_quantification_user` As `u` ON `q`.`quantification_id`=`u`.`quantification_id` WHERE `q`.`quantification_post_type` = 3 AND `q`.`is_del` = 1 AND `u`.`user_id` = $pid AND FIND_IN_SET('$workid', q.quantification_user)";
        $user_list = $this->M_quantification_user_map->querylist($sql1);


        if(!empty($user_list)){
            //已生成过当前PID任务
            foreach($user_list as $k=>$v){
                //这个人在这个末班下要做的网格任务
                $user_map  = array();
                $sql = "select * from t_quantification_map where quantification_id=".$v['quantification_id']." and is_del=1";
                $user_map = $this->M_quantification_user_map->querylist($sql);
                if(!empty($user_map)){
                    foreach($user_map as $ak=>$av){
                        //查询当前时间是否已有任务（当前时间段的任务）
                        $tables1 = array('t_quantification_user_map'=>'q');
                        $user_list1 = $this->M_quantification_user_map->getJoinList($tables1,null,'q.*',array('q.quantification_user_id'=>$v['userid'],'q.quantification_map_id'=>$av['quantification_map_id'],'q.grid_id'=>$av['grid_id'],'q.user_id'=>$pid,'q.start_time <='=>$time,'q.end_time>='=>$time),null,null);

                        if(!empty($user_list1))//有当前时间段的任务并且离结束时间大于半小时才会生成任务
                        {
                            continue;
                        }
                        else
                        {

                            //晚上1点到5点之间，2小时频率的要改为4小时频率
                            if((($n >= 1) && ($av['quantification_task_cycle_h'] == 2)) && (($n <=4) && ($av['quantification_task_cycle_h'] == 2)))
                            {
                                $av['quantification_task_cycle_h'] = 4;
                            }

//                        $sql = "SELECT id FROM t_quantification_user_map WHERE qu_user_id=".$v['userid']." and qu_map_id=".$av['map_id']." and PID=".$pid;
//                        $count = $this->M_quantification_user_map->querylist($sql);
//                        $count = count($count)+1;
                            $h = ($n-1)/$av['quantification_task_cycle_h'];
                            $h = floor($h);
//                        $h = intval($h);
                            $h = $av['quantification_task_cycle_h']*$h+1;
//                        $h=($av['h']*$count)+1;
                            $todayTime= mktime($h,0,0,$m,$d,$y);
                            //计算结束时间
                            $map_time_i = ($av['quantification_task_cycle_d'] * 24 * 60) + ($av['quantification_task_cycle_h'] * 60);
                            $map_time_jiange = $map_time_i * 60;// 间隔时间 秒
                            $data = array(
                                'quantification_user_id'=>$v['userid'],
                                'quantification_map_id'=>$av['quantification_map_id'],
                                'grid_id'=>$av['grid_id'],
                                'start_time'=>$todayTime,
                                'end_time'=>$todayTime + $map_time_jiange,
                                'number'=>$av['quantification_task_number'],
                                'quantification_user_map_addtime'=>$time,
                                'user_id'=>$pid,
                                'finish_number'=>0,
                            );

                            $lists = $this->db->select('quantification_user_map_id')
                            			->from('t_quantification_user_map')
                            			->where(['start_time' => $data['start_time'],'end_time' => $data['end_time'],'grid_id' => $data['grid_id'],'status' => 2])
                            			->get()
                            			->row_array();
                            if(!empty($lists['quantification_user_map_id']))
                            {
                            	$data['is_del'] = 2;
                            }

//                        if($data['end_time']-$time < 1800)
//                        {
//                            continue;
//                        }
//                        else
//                        {
                            $p = $this->M_quantification_user_map->saveData($data);
                            $dd['info'] = '添加了';
//                                echo "添加";
//                            }
//                            else
//                            {
//                            }
//                        }
                        }
                    }
                }
            }
        }
        else
        {
            foreach ($quanti as $value)
            {
                //还没有生成当前PID的任务
                $data = array(
                    'user_id' =>$pid,
                    'quantification_id' => $value['quantification_id'],
                    'quantification_user_taketime' => $value['quantification_start_time'],
                    'quantification_user_status' => 1,
                    'quantification_user_remark' => '',
                    'quantification_user_check' => $value['quantification_check_cycle'],
                    'quantification_user_addtime' => $time,
                );
                //用户每月任务
                $rid = $this->M_quantification_user->saveData($data);
                $user_map  = array();
                $sql = "select * from t_quantification_map where quantification_id=".$value['quantification_id']." and is_del=1";
                $user_map = $this->M_quantification_user_map->querylist($sql);
                foreach($user_map as $ak=>$av){
                    //晚上1点到5点之间，2小时频率的要改为4小时频率
                    if((($n >= 1) && ($av['quantification_task_cycle_h'] == 2)) && (($n <=4) && ($av['quantification_task_cycle_h'] == 2)))
                    {
                        $av['quantification_task_cycle_h'] = 4;
                    }

                    $h = ($n-1)/$av['quantification_task_cycle_h'];
                    $h = floor($h);
//              $h = intval($h);
                    $h = $av['quantification_task_cycle_h']*$h+1;

                    $todayTime= mktime($h,0,0,$m,$d,$y);
                    //获取当前的时间（几点$n）
                    //计算结束时间
                    $map_time_i = ($av['quantification_task_cycle_d'] * 24 * 60) + ($av['quantification_task_cycle_h'] * 60);
                    $map_time_jiange = $map_time_i * 60;// 间隔时间 秒
                    $data = array(
                        'quantification_user_id'=>$rid,
                        'quantification_map_id'=>$av['quantification_map_id'],
                        'grid_id'=>$av['grid_id'],
                        'start_time'=>$todayTime,
                        'end_time'=>$todayTime + $map_time_jiange,
                        'number'=>$av['quantification_task_number'],
                        'finish_number'=>0,
                        'quantification_user_map_addtime'=>$time,
                        'user_id'=>$pid,
                    );

                    $lists = $this->db->select('quantification_user_map_id')
                            			->from('t_quantification_user_map')
                            			->where(['start_time' => $data['start_time'],'end_time' => $data['end_time'],'grid_id' => $data['grid_id'],'status' => 2])
                            			->get()
                            			->row_array();
                        if(!empty($lists['quantification_user_map_id']))
                        {
                        	$data['is_del'] = 2;
                        }


//                if($data['end_time']-$time < 1800)
//                {
//                    continue;
//                }
//                else
//                {
                    $p = $this->M_quantification_user_map->saveData($data);
                    $dd['info'] = '添加了';
//                }
//            echo "添加";
                }
            }
        }
        // exit(json_encode(array('code'=>0,'info'=>$dd['info'])));
        // $this->printJson_data($dd);
    }
   	//登岗生成应急任务
	public function create_em_task($userid,$workid){

		// $userid  = $this->input->get_post('userid');
		// $workid  = $this->input->get_post('workid');
		$sql = "select * from t_emergency_mouldaccept m left join t_emergency_levelstep l on m.stepid=l.id left join t_emergency e on e.emergency_id=l.emid where m.pid={$workid} and m.type=2 and is_active=1";
		$info = $this->M_emergency->querylist($sql);
		if(empty($info)){
			return false;
		}else{
			foreach ($info as $key => $value) {
				$content = substr($value['content'], 0,120);
				$sql = "select * from t_emergency_list where emid={$value['emergency_id']} and flag=2";
				$info = $this->db->query($sql)->row_array();
				// $sql = "select * from t_emergency_mouldaccept where pid={$userid} and stepid={$value['stepid']} and pid={$workid} and type=2";
				$sql1 = "select * from t_emergency_task_sub where pid={$userid} and stepid={$value['stepid']} and emlid={$value['id']}";
				if($this->db->query($sql1)->num_rows()>0){
	                            		continue;
				}
				$sql = "select * from t_user where is_online=1 and post_id=$workid and user_id={$userid}";
				$res = $this->db->query($sql)->row_array();
				if(!empty($res)){
						$data2= array(
							'pid'=>$userid,
							'pname'=>$res['user_name'],
							'stepid'=>$value['stepid'],
							'status'=>0,
							'type'=>2,
							'postid'=>$workid,
							'addtime'=>time(),
							'emlid'=>$info['id'],
							);
						$send = $this->push(1,$userid,$value['emergency_name'],$content,$value['stepid'],8);
						$insert_id2 = $this->M_emergency_task_sub->saveData($data2);
				}
			}

		}
		
	}

     //登录岗位生成作业任务
    public function create_post_task($userid,$workid)
    {
//        $userid = getParam($this->input->get_post("userid", true), 'int');//用户id
//        $workid = getParam($this->input->get_post("workid", true), 'int');//岗位id
//        $userid = "63";
//        $workid = "8"; //64,81
       // $userid=1471;
       // $workid=97;
       // 列车的flowid；
       $userid = intval($userid);
        $time = time();
        $string = "";
        $sql = "select t.flow_id,t.task_id,t.task_id,t.task_title,t.task_name,t.task_content,t.task_style,p.grid_id from t_train_task t LEFT JOIN t_train_flow f on t.flow_id=f.train_flow_id
                LEFT JOIN t_platform p ON f.platform_id=p.platform_id where f.train_status=1 AND f.train_flow_statu<>1 AND f.is_open=1 AND t.post_type_id=2 AND t.task_status=4 AND FIND_IN_SET('$workid',t.post_id) GROUP by t.task_id";
        $res = $this->db->query($sql)->result_array();
        if(empty($res))
        {
        	return false;
            // exit(json_encode(array('code'=>1,'data'=>'','info'=>'无任务')));
        }
        else
        {
            foreach ($res as $key => $value) {
                        $sql ="select * from t_train_task_sub where receive_user_id={$userid} AND task_id={$value['task_id']}";
                        if($this->db->query($sql)->num_rows()>0)
                        {
                            // exit(json_encode(array('code'=>1,'data'=>'','info'=>'已存在任务')));
                            continue;
                         }
                //判断列车站台是否与岗位负责站台一致
                //作业岗位
                $sql ="select post_id,post_user,post_grid from t_post where post_type_id=2 AND post_id=$workid";
                $res = $this->db->query($sql)->result_array();

                foreach ($res as $kk=>$vv){
                    $post_grid = explode(',',$vv['post_grid']);//责任网格ID
                    $is_true = false;
                    if($value['task_style'] == 1){
                        foreach ($post_grid as $key1=>$value1){
                            //列车所属站台
                            if($value1 == $value['grid_id']){
                                $is_true = true;
                                break;
                            }
                        }
                    }else{
                        $is_true = true;
                    }
                    if($is_true){
                    	// echo $userid.'********';
                    	// echo $value['task_title'].'********';
                    	// echo $value['task_content'].'********';
                    	// echo $value['task_id'].'********';
                        // $send = $this->push(2391,1471,$value['task_title'],$value['task_content'],$value['task_id'],7);
                        $send = $this->push(2391,$userid,$value['task_title'],$value['task_name'],$value['task_id'],7);
                        $string .= "({$value['task_id']},{$userid},'{$userid}',{$time},0,{$workid},{$value['flow_id']}),";
                    }
                }
             }
            $string = rtrim($string, ',');

        }
        if(empty($string) || $string==''){
                // exit(json_encode(array('code'=>1,'data'=>'','info'=>'已存在任务')));
                // 
                return false;
        }else{
                $usql ="insert into t_train_task_sub(task_id,accepitid,receive_user_id,pub_time,work_status,post_id,flow_id) VALUES {$string}";
                $res1 = $this->db->query($usql);
                if($res1)
                {
                	return true;
                    // exit(json_encode(array('code'=>0,'data'=>'','info'=>'成功')));
                }
                else
                {
                	return false;
                    // exit(json_encode(array('code'=>1,'data'=>'','info'=>'失败')));
        		}
        }
    }

	/*
	    	搜索
	*/
    	public function user_search()
    	{

    		$name = $this->input->post('name');
    		$list = $this->db->select('user_id,user_account,user_name')
    				->from('t_user')
    				->like('user_account',$name,'both')
    				->or_like('user_name',$name,'both')
    				->get()
    				->result_array();
    		if($list)
    		{
    			$res['code'] = 0;
    			$res['info'] = "获取成功";
    			$res['data'] = $list;
    		}else{
    			$res['code'] = 1;
    			$res['info'] = "暂无数据";
    			$res['data'] = array();
    		}

    		echo json_encode($res);

    	}

    	/*
    		根据id判断是否允许操作
    	 */
    	public function user_done()
	{

		$user_id = $this->input->post('user_id');
		// $user_id = 244;
		$result = $this->db->select('has_role as roles')
			     	->from('t_user')
			     	->where('user_id',$user_id)
			     	->get()
			     	->row_array();
		$intros = array();
		if(!empty($result['roles']))
		{
			$roles = explode(',',$result['roles']);
			$result1 = $this->db->select('rights')
					->from('t_role')
					->where_in('role_id',$roles)
					->get()
					->result_array();
			foreach($result1 as $k1 => $v1)
			{
				$has_intro[] = explode(',',$v1['rights']);
			}
			foreach($has_intro as $k => $v)
			{
				foreach($v as $key => $value)
				{
					if(!in_array($value,$intros))
					{
						$intros[] = $value;
					}
				}
			}
		}
		/*
			APP端权限
		 */
		$bao['login_app'] = false;
		$bao['see_task'] = false;
		$bao['see_four_plan'] = false;
		$bao['voice_call'] = false;
		$bao['video_conference'] = false;
		$bao['device_task'] = false;
		$bao['device_repair'] = false;
		$bao['device_inspect'] = false;
		$bao['point_video'] = false;

		if(in_array(3,$intros))
		{
			$bao['login_app'] = true;
		}
		if(in_array(12,$intros))
		{
			$bao['see_task'] = true;
		}
		if(in_array(13,$intros))
		{
			$bao['see_four_plan'] = true;
		}
		if(in_array(14,$intros))
		{
			$bao['voice_call'] = true;
		}
		if(in_array(15,$intros))
		{
			$bao['video_conference'] = true;
		}
		if(in_array(16,$intros))
		{
			$bao['device_task'] = true;
		}
		if(in_array(17,$intros))
		{
			$bao['device_repair'] = true;
		}
		if(in_array(18,$intros))
		{
			$bao['device_inspect'] = true;
		}
		if(in_array(19,$intros))
		{
			$bao['point_video'] = true;
		}

		if($bao)
		{
			$res['code'] = 0;
			$res['info'] = "获取成功";
			$res['data'] = $bao;
		}else{
			$res['code'] = 1;
			$res['info'] = "暂无数据";
			$res['data'] = array();
		}
		
		echo json_encode($res);

	}

}